﻿using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.RedisCache.ProtoBuf
{
    public class ProroBufRedisSerializer : IRedisSerializer
    {
        public object Deserialize(string value)
        {
            var serializedStr = value.TrimStart(new char[] { '"' }).Substring(ProtoBufPrefix.Length).TrimEnd(new char[] { '"' });
            var typeSeperatorIndex = serializedStr.IndexOf(TypeSeperator, StringComparison.OrdinalIgnoreCase);
            var type = Type.GetType(serializedStr.Substring(0, typeSeperatorIndex));
            var base64str = serializedStr.Substring(typeSeperatorIndex + 1);
            var byteAfter64 = Convert.FromBase64String(base64str);

            using (var memoryStream = new MemoryStream(byteAfter64))
            {
                return Serializer.Deserialize(type, memoryStream);
            }
        }

        public string Serialize(object value, Type type)
        {
            using (var stream = new MemoryStream())
            {
                Serializer.Serialize(stream, value);
                var bytes = stream.ToArray();
                var base64str = Convert.ToBase64String(bytes, 0, bytes.Length);
                return string.Format(
                "{0}{1}{2}{3}",
                ProtoBufPrefix,
                type.AssemblyQualifiedName,
                TypeSeperator,
                base64str
                );
            }
        }

        private const string TypeSeperator = "|";
        private const string ProtoBufPrefix = "ShanYuProtoBuf^";
    }
}
